package com.liziba.classloader;

import java.io.*;

/**
 * <p>
 *      文件系统类加载器
 * </p>
 *
 * @Author: Liziba
 * @Date: 2021/5/31 23:04
 */
public class FileSystemClassLoader extends ClassLoader {

    /** 指定文件路径 */
    private String rootDir;

    public FileSystemClassLoader(String rootDir) {
        this.rootDir = rootDir;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] data = getClassByteData(name);
        if (data == null || data.length == 0) {
            throw new ClassNotFoundException();
        } else {
            return defineClass(name, data, 0, data.length);
        }
    }


    /**
     * 读取类的字节流、获取字节数组
     *
     * @param className
     * @return
     */
    private byte[] getClassByteData(String className) {
        String path = classNameCovertToPath(className);
        try {
            InputStream in = new FileInputStream(path);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024 * 4];
            int len = 0;
            while ((len = in.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            return baos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 类权限定名转绝对路径
     *
     * @param className
     * @return
     */
    private String classNameCovertToPath(String className) {
        return rootDir + File.separatorChar + className.replace('.', File.separatorChar) + ".class";
    }

}
